//
//  ScoreParentViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-14.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ScoreParentViewController.h"
#import "RateView.h"
#import "ParentRateView.h"
#import <UIImageView+AFNetworking.h>
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"


@interface ScoreParentViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *photo;
@property (weak, nonatomic) IBOutlet UILabel *datetime;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (assign, nonatomic)BOOL canScroll;
@end

@implementation ScoreParentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.canScroll = YES;
    // Do any additional setup after loading the view.
    
    CALayer *layer = [self.photo layer];
    layer.borderColor = [[UIColor whiteColor] CGColor];
    layer.borderWidth = 2.0f;
    
    self.photo.image = self.appDelegate.userPhoto;
    
//    CGSize contentSize = CGSizeMake(self.scrollView.frame.size.width, self.scrollView.frame.size.height);
    self.scrollView.contentSize = CGSizeMake(0, self.scrollView.frame.size.height);
    
    self.scrollView.contentOffset = CGPointZero;
    
    
    [self loadRemoteData:nil twoPage:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadRemoteData:(NSString *)datetime twoPage:(BOOL)twoPage{
    NSString *uriString = [NSString stringWithFormat:@"Score/%@.json" , self.appDelegate.user[@"childId"]];
    //    NSString *uriString = [NSString stringWithFormat:@"Score/%@.json" , appDelegate.user[@"childId"]];
    
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey, @"scoreDate":datetime == nil?[NSNull null]:datetime};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            if (responseObject[@"data"] != [NSNull null] && [[responseObject[@"data"] allKeys] count ]!= 0) {
                if (twoPage) {
                    [self addScoreView:0 viewData:responseObject[@"data"]offsetX:0];
                    [self loadRemoteData:responseObject[@"data"][@"scoreDate"] twoPage:NO];
                }else{
                    [self addScoreView:0 viewData:responseObject[@"data"]offsetX:self.scrollView.frame.size.width];
                }
            }else{
                self.canScroll = NO;
                self.datetime.text = @"无评分记录";
            }
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
}

- (void)addScoreView:(NSUInteger)pageNumber viewData:(NSDictionary *)data offsetX:(CGFloat)offsetX{
    CGSize contentSize = self.scrollView.contentSize;
    self.scrollView.contentSize = CGSizeMake(contentSize.width + self.scrollView.frame.size.width, contentSize.height);
    
    
    for (UIView *subView in self.scrollView.subviews) {
        CGRect rect = subView.frame;
        rect.origin.x += self.scrollView.frame.size.width;
        
        subView.frame = rect;
    }
    
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    if (offsetX == 0) {
        [self.datetime setText:data[@"scoreDate"]];
    }
    
    
    NSArray *nibViews=[[NSBundle mainBundle] loadNibNamed:@"ParentRateView" owner:self options:nil];
    ParentRateView *rateView = nibViews[0];
    rateView.data = data;
    CGRect scrollFrame = self.scrollView.frame;
    rateView.frame = CGRectMake(scrollFrame.size.width*pageNumber, 0, scrollFrame.size.width, scrollFrame.size.height);
    
    rateView.datetime = self.datetime.text;
    [self.scrollView addSubview:rateView];

    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



//???: 这种方法会不会爆内存啊
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"scrollViewDidEndDecelerating %@", NSStringFromCGPoint(scrollView.contentOffset));
    
    
    NSString *parameter;
    for (UIView *subView in scrollView.subviews) {
        if (CGRectContainsPoint(subView.frame, scrollView.contentOffset)) {
            parameter = [subView valueForKey:@"datetime"];
        }
        
    }
    if (parameter == nil) {
        [self.datetime setText:@"无评分记录"];
    }else{
        [self.datetime setText:parameter];
    }
    
    
    CGPoint offset = scrollView.contentOffset;
    if (CGPointEqualToPoint(offset, CGPointZero)&&self.canScroll) {
        
        [self loadRemoteData:parameter twoPage:NO];
        
    }
    
}
@end
